package com.hdax.dmw.scheduler.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dmw.common.exceptions.OrderException;
import com.hdax.dmw.common.utils.Result;
import com.hdax.dmw.common.utils.ResultGenerator;
import com.hdax.dmw.common.utils.ServiceResultEnum;
import com.hdax.dmw.entity.scheduler.SchedulerSeat;
import com.hdax.dmw.entity.scheduler.TxMsg;
import com.hdax.dmw.scheduler.dtos.SchedulerDto;
import com.hdax.dmw.scheduler.dtos.SeatArrayDto;
import com.hdax.dmw.scheduler.service.SchedulerSeatService;
import com.hdax.dmw.scheduler.mappers.SchedulerSeatMapper;
import com.hdax.dmw.scheduler.service.TxMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author guoyisha
* @description 针对表【dm_scheduler_seat(排期座位表)】的数据库操作Service实现
* @createDate 2023-07-24 14:56:40
*/
@Service
public class SchedulerSeatServiceImpl extends ServiceImpl<SchedulerSeatMapper, SchedulerSeat>
    implements SchedulerSeatService{


    @Autowired
    private TxMsgService txMsgService;

    @Override
    public int getSaleCount(Long scheduleId,Integer areaLevel) {
        QueryWrapper<SchedulerSeat> queryWrapper
                 = new QueryWrapper<>();
        queryWrapper.eq("scheduleId",scheduleId);
        queryWrapper.isNotNull("orderNo");
        queryWrapper.isNotNull("userId");
        queryWrapper.eq("areaLevel",areaLevel);
        queryWrapper.in("status",2,3);
        int saleCount = (int)count(queryWrapper);
        return saleCount;
    }

    @Override
    public List<SchedulerSeat> seatInfoList(Long scheduleId) {
        QueryWrapper<SchedulerSeat> queryWrapper
                = new QueryWrapper<>();
        queryWrapper.eq("scheduleId",scheduleId);
        queryWrapper.isNull("orderNo");
        queryWrapper.isNull("userId");
        queryWrapper.eq("status",1);
        List<SchedulerSeat> list = list(queryWrapper);
        return list;
    }

    @Override
    public Result<SeatArrayDto> seatArray(Long scheduleId) {
        List<SchedulerSeat> list = list(new QueryWrapper<SchedulerSeat>().eq("scheduleId", scheduleId));
        Map<Integer, List<SchedulerSeat>> map = list.stream().collect(Collectors.groupingBy(SchedulerSeat::getX));

        SeatArrayDto dto = new SeatArrayDto();
        List<String> strs = new ArrayList<>();
        map.keySet().forEach(x->{
            List<SchedulerSeat> ys = map.get(x);
            StringBuffer buffer = new StringBuffer();
            ys.forEach(seat->{
                switch (seat.getAreaLevel()) {
                    case 1:
                        buffer.append("a");
                        break;
                    case 2:
                        buffer.append("b");
                        break;
                    case 3:
                        buffer.append("c");
                        break;
                    default:
                        buffer.append("_");
                        break;
                }
            });
            strs.add(buffer.toString());
            dto.setSeatArray(strs);
        });
        return ResultGenerator.genSuccessResult(dto);
    }

    @Override
    public SchedulerSeat detail(Long scheduleId, Integer x, Integer y) {
        return baseMapper.detail(x, y, scheduleId);
    }

    @Override
    @Transactional
    public boolean updateSeats(String jsonStr) {
        TxMsg txMsg = JSONUtil.toBean(jsonStr, TxMsg.class);
        //新增本地消息表
        txMsgService.save(txMsg);
        String msg = txMsg.getMsg();
        Map map = JSONUtil.toBean(msg, Map.class);
        String orderNo = map.get("orderNo").toString();
        Long scheduleId = Long.parseLong(map.get("scheduleId").toString());
        Long userId = Long.parseLong(map.get("userId").toString());
        String[] seats = ((JSONArray)map.get("seatPositions")).toArray(new String[0]);

        List<SchedulerSeat> schedulerSeats = new ArrayList<>();
        for (int i = 0; i < seats.length; i++) {
            String[] position = seats[i].split("_");
            Integer x = Integer.parseInt(position[0]);
            Integer y = Integer.parseInt(position[1]);
            //每一个座位
            SchedulerSeat seatDetail = detail(scheduleId, x, y);
            if(seatDetail.getOrderNo() != null &&
                    seatDetail.getUserId() != null &&
                    seatDetail.getStatus() != 1){
                throw new OrderException(ServiceResultEnum.ORDER_ITEM_NULL_ERROR);
            }
            seatDetail.setOrderNo(orderNo);
            seatDetail.setUserId(userId);
            seatDetail.setStatus(2);
            schedulerSeats.add(seatDetail);
        }
        updateBatchById(schedulerSeats);
        //修改本地消息表
        txMsg.setVersion(txMsg.getVersion()+1);
        txMsg.setMsgResult(1);
        txMsgService.updateById(txMsg);
        return true;
    }
}




